package com.ruoyi.manage.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.RoleKeyEnum;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.manage.entity.order.OrderDistributeDto;
import com.ruoyi.manage.entity.order.OrderDto;
import com.ruoyi.manage.service.IOrderDistributeService;
import com.ruoyi.system.mapper.SysRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.manage.mapper.OrdersMapper;
import com.ruoyi.manage.domain.Orders;
import com.ruoyi.manage.service.IOrdersService;

/**
 * 所有订单Service业务层处理
 *
 * @author ruoyi
 * @date 2024-10-22
 */
@Slf4j
@Service
public class OrdersServiceImpl implements IOrdersService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private IOrderDistributeService IOrderDistributeService;

    /**
     * 查询所有订单
     *
     * @param ID 所有订单主键
     * @return 所有订单
     */
    @Override
    public Orders selectOrdersByID(Long ID) {
        return ordersMapper.selectOrdersByID(ID);
    }

    /**
     * 查询所有订单列表
     *
     * @param orders 所有订单
     * @return 所有订单
     */
    @Override
    public List<Orders> selectOrdersList(Orders orders) {
        OrderDto orderDto = new OrderDto();
        BeanUtil.copyProperties(orders, orderDto);

        List<Orders> resultList;
        if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            List<SysRole> roles = loginUser.getUser().getRoles();
            List<SysRole> bossRoles = roles.stream().filter(item -> CharSequenceUtil.equals(item.getRoleKey(), "boss")).collect(Collectors.toList());
            //如果不为boss
            if (bossRoles.isEmpty()) {
                Long userId = SecurityUtils.getUserId();
                if (roles.size() > 1) {
                    orderDto.setWriterId(userId);
                    orderDto.setManagerId(userId);
                } else {
                    SysRole sysRole = roles.get(0);
                    String roleKey = sysRole.getRoleKey();
                    switch (Objects.requireNonNull(RoleKeyEnum.getRoleKey(roleKey))) {
                        case MANAGER:
                            orderDto.setManagerId(userId);
                            break;
                        case WRITER:
                            //当前用户如果是写手，只能查找自己的订单
                            orders.setWriterId(userId);
                            break;
                        default:
                    }
                }
            }
        }
        resultList = this.ordersMapper.selectOrdersManagerWriterList(orderDto);
        if (CollUtil.isNotEmpty(resultList)) {
            resultList.forEach(item -> {
                if (ObjectUtil.isNull(item.getOrderRequire())) {
                    item.setOrderRequire("");
                }
            });
        }
        return resultList;
    }

    private List<Orders> findOrderByParams(String roleKey, Long userId, OrderDto orders) {
        List<Orders> resultList = null;
        switch (Objects.requireNonNull(RoleKeyEnum.getRoleKey(roleKey))) {
            case MANAGER:
                orders.setManagerId(userId);
                resultList = ordersMapper.selectOrdersManagerWriterList(orders);
                break;
            case WRITER:
                //当前用户如果是写手，只能查找自己的订单
                orders.setWriterId(userId);
                resultList = ordersMapper.selectOrdersManagerWriterList(orders);
                break;
            default:
        }
        return resultList;
    }

    /**
     * 新增所有订单
     *
     * @param orders 所有订单
     * @return 结果
     */
    @Override
    public int insertOrders(Orders orders) {
        //判断订单编号订单名称是否已经存在
        String orderId = orders.getOrderId();
        String orderName = orders.getOrderName();
        int orderIdNumber = this.ordersMapper.getOrderNumber(orderId, null, null);
        if (orderIdNumber > 0) {
            throw new ServiceException("订单编号已存在");
        }
        int orderNameNumber = this.ordersMapper.getOrderNumber(null, orderName, null);
        if (orderNameNumber > 0) {
            throw new ServiceException("订单名称已存在");
        }

        List<SysDictData> orderStatusList = DictUtils.getDictCache("order_status");
        Optional<SysDictData> first = orderStatusList.stream().filter(item -> item.getDictCode().compareTo(100L) == 0).findFirst();
        String orderStatus = first.isPresent() ? first.get().getDictValue() : "1";

        LoginUser loginUser = SecurityUtils.getLoginUser();
        orders.setCreateBy(loginUser.getUsername());
        orders.setCreateTime(new Date());
        orders.setUpdateBy(loginUser.getUsername());
        orders.setUpdateTime(new Date());
        orders.setOrderStatus(orderStatus);

        return ordersMapper.insertOrders(orders);
    }

    /**
     * 修改所有订单
     *
     * @param orders 所有订单
     * @return 结果
     */
    @Override
    public int updateOrders(Orders orders) {
        Long id = orders.getID();
        String orderId = orders.getOrderId();
        String orderName = orders.getOrderName();
        int orderIdNumber = this.ordersMapper.getOrderNumber(orderId, null, id);
        if (orderIdNumber > 0) {
            throw new ServiceException("订单编号已存在");
        }
        int orderNameNumber = this.ordersMapper.getOrderNumber(null, orderName, id);
        if (orderNameNumber > 0) {
            throw new ServiceException("订单名称已存在");
        }

        return ordersMapper.updateOrders(orders);
    }

    /**
     * 批量删除所有订单
     *
     * @param IDs 需要删除的所有订单主键
     * @return 结果
     */
    @Override
    public int deleteOrdersByIDs(Long[] IDs) {
        return ordersMapper.deleteOrdersByIDs(IDs);
    }

    /**
     * 删除所有订单信息
     *
     * @param ID 所有订单主键
     * @return 结果
     */
    @Override
    public int deleteOrdersByID(Long ID) {
        return ordersMapper.deleteOrdersByID(ID);
    }

    @Override
    public void orderDistributeToWriter(OrderDistributeDto orderDistribute) {

    }

    @Override
    public void updateStatus(Orders orders) {
        Orders waitUpdateOrder = this.ordersMapper.selectByOrderId(orders.getOrderId());
        if (ObjectUtil.isNull(waitUpdateOrder)) {
            throw new ServiceException("订单信息不存在");
        }
        waitUpdateOrder.setOrderStatus(orders.getOrderStatus());
        waitUpdateOrder.setUpdateBy(SecurityUtils.getUsername());
        waitUpdateOrder.setUpdateTime(new Date());
        this.ordersMapper.updateOrders(waitUpdateOrder);
    }
}
